package com.levi.rabbitmq.topic;

import com.rabbitmq.client.BuiltinExchangeType;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.TimeoutException;

public class TopicProducer {

    public static final String EXCHANGE_NAME = "topic";

    public static void main(String[] args) throws IOException, TimeoutException {
        //创建连接工厂
        ConnectionFactory connectionFactory = new ConnectionFactory();
        //设置rabbitmq地址
        connectionFactory.setHost("192.168.177.129");
        connectionFactory.setPort(5672);
        connectionFactory.setUsername("admin");
        connectionFactory.setPassword("admin");
        //建立连接
        Connection connection = connectionFactory.newConnection();
        //获得信道
        Channel channel = connection.createChannel();
        //设置交换机模式为fanout广播模式
        channel.exchangeDeclare(EXCHANGE_NAME, BuiltinExchangeType.TOPIC);
        
        //发送消息
        String message = "topic animal world";
        String[] routingkeys = new String[9];
        routingkeys[0] = " quick.orange.rabbit";
        routingkeys[1] = "quick.pink.rabbit";
        routingkeys[2] = "lazy.orange.rabbit";
        routingkeys[3] = "lazy.pink.elephant";
        routingkeys[4] = "lazy.orange.elephant";
        routingkeys[5] = "quick.orange.elephant";
        routingkeys[6] = "orange";
        routingkeys[7] = "quick.pink.male.rabbit";
        routingkeys[8] = "lazy.pink.male.rabbit";

        for (int i = 0; i < 9; i++) {
            //                       交换机     队列名称         额外配置          要发送的消息
            channel.basicPublish(EXCHANGE_NAME, routingkeys[i], null, message.getBytes(StandardCharsets.UTF_8));
            System.out.println(routingkeys[i]+"    发送了消息: "+ message);
        }
        //关闭连接
        channel.close();
        connection.close();
    }
}
